package com.apes.scm.card.service;

import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.filereader.xml.SimpleApesElement;
import com.apes.scm.card.model.InsuranceCard;
import com.apes.scm.card.repository.InsuranceCardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program:
 * @description:
 * @author: lws
 * @create: 2023/3/7 16:18
 **/
@Service
public class InsuranceCardService extends DomainService {

    @Autowired
    private InsuranceCardRepository insuranceCardRepository;

    public InsuranceCard save(SimpleRequest request){
        InsuranceCard insuranceCard = request.getO(InsuranceCard.class);
        checkDistinctProduct(insuranceCard); // 不能存在重复商品
        insuranceCard.setState("create");
        return insuranceCardRepository.saveAndFlush(insuranceCard);
    }

    public InsuranceCard update(SimpleRequest request){
        InsuranceCard insuranceCard = request.getO(InsuranceCard.class);
        return insuranceCardRepository.saveAndFlush(insuranceCard);
    }

    public InsuranceCard delete(SimpleRequest request){
        InsuranceCard insuranceCard = request.getO(InsuranceCard.class);
        insuranceCard.setState("delete");
        return insuranceCardRepository.saveAndFlush(insuranceCard);
    }

    public void checkDistinctProduct(InsuranceCard insuranceCard){
        List<InsuranceCard> insuranceCards = insuranceCardRepository.findAll(JpaDsl.toCriteriaByEq("product.id", insuranceCard.getProduct().getId()));
        if (insuranceCards != null && !insuranceCards.isEmpty()) throw new RuntimeException("存在重复商品的分销单！");
    }
}
